import {_decorator, Component, find, Node, Vec3} from 'cc';
import {PlayerHPViewModel} from "db://assets/Scripts/MVC/Player/hp/PlayerHPViewModel";
import {PlayerHPUiState} from "db://assets/Scripts/MVC/Player/hp/PlayerHPUiState";
import {EventManager} from "db://assets/Scripts/Common/EventManager";
import {EventType} from "db://assets/Scripts/Common/EventType";
import {NodePath} from "db://assets/Scripts/Common/NodePath";
import {PlayerController} from "db://assets/Scripts/MVC/Player/PlayerController";

const {ccclass, property} = _decorator;

/**
 * 生命值Controller
 */
@ccclass('PlayerHPController')
export class PlayerHPController extends Component {
    /**
     * 生命值ViewModel
     */
    private viewModel: PlayerHPViewModel = new PlayerHPViewModel();
    /**
     * 生命值UiState
     */
    private uiState: PlayerHPUiState = this.viewModel.uiState;

    onEnable() {
        // 注册重新开始事件
        EventManager.on(EventType.RESTART, this.onRestart, this);
    }

    onDisable() {
        // 取消注册重新开始事件
        EventManager.off(EventType.RESTART, this.onRestart, this);
    }

    start() {
        // 查找玩家节点
        this.uiState.playerNode = find(NodePath.PLAYER);
        // 设置玩家Controller
        this.uiState.playerController = this.uiState.playerNode.getComponent(PlayerController);
    }

    update(deltaTime: number) {
        // 刷新生命值
        this.refreshHPBar();
    }

    /**
     * 重新开始事件
     */
    private onRestart() {
        // 查找玩家节点
        this.uiState.playerNode = find(NodePath.PLAYER);
        // 设置玩家Controller
        this.uiState.playerController = this.uiState.playerNode.getComponent(PlayerController);
    }

    /**
     * 刷新生命值
     */
    private refreshHPBar() {
        // 生命值无变化
        if (this.uiState.currentHP === this.uiState.playerController.uiState.hp) {
            return;
        }

        // 更新生命条
        const x = (this.uiState.playerController.uiState.hp / this.uiState.playerController.uiState.maxHP).toFixed(2);
        this.node.scale = new Vec3(Number.parseFloat(x), 1, 1);

        // 记录当前生命值
        this.uiState.currentHP = this.uiState.playerController.uiState.hp;
    }
}